#include "widget.h"
#include "ui_widget.h"
#include <QTimer>
#include <QDateTime>
#include <QString>
#include<QButtonGroup>
#include<remindadd.h>
#include "storageadd.h"
#include "storageitem.h"
#include "QListWidgetItem"
#include "QTreeWidgetItem"
#include "reminditem.h"
#include "dish.h"
#include "dishrecommendunit.h"
#include <QList>
#include "option.h"
#include "optiongroup.h"
#include "optionunit.h"
#include "storageedit.h"
#include <QScroller>
#include <QInputDialog>


Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    qDebug() << "OpenSSL支持情况:" << QSslSocket::supportsSsl();
    qDebug()<<"QSslSocket="<<QSslSocket::sslLibraryBuildVersionString();
    ui->setupUi(this);
    initView();
    initTime();
    initDish();
    initOption();
    initStorage();
    initRemind();
}


void Widget::initView()
{
    showFullScreen();
    ui->fridgeInfo->setCurrentIndex(0);
    // 初始化默认stack
    ui->stackedWidget->setCurrentIndex(0);

    // 关联左侧按键
    connect(ui->btn_storage,&QToolButton::clicked,[=](){
        ui->stackedWidget->setCurrentIndex(0);
    });
    connect(ui->btn_remind,&QToolButton::clicked,[=](){
        ui->stackedWidget->setCurrentIndex(1);
    });
    connect(ui->btn_diet,&QToolButton::clicked,[=](){
        if(token!=NULL){
            ui->stackedWidget->setCurrentIndex(2);
            api->getRecommendDish();
        }
        else
            ui->stackedWidget->setCurrentIndex(5);
    });
    connect(api,&Api::getRecommendDishSuccess,this,&Widget::updateDishRecommend);
    connect(ui->btn_opt,&QToolButton::clicked,[=](){
        ui->stackedWidget->setCurrentIndex(4);
    });
    // 绑定获取冰箱信息
    connect(ui->btn_fridge_info,&QToolButton::clicked,this,[=](){
       api->infoCer();
    });
    connect(api,&Api::infoCerSuccess,this,&Widget::updateFridgeInfo);
    connect(ui->btn_logout,&QToolButton::clicked,this,[=](){
       QString test = NULL;
       this->token = test;
       ui->stackedWidget->setCurrentIndex(5);
    });
    connect(ui->btn_my,&QToolButton::clicked,[=](){
        // 验证token是否有效，这里使用token是否为null来验证，如果是提示登录，显示用户信息
        // 后续通过验证token是否有效的函数来验证
        if(token!=NULL)
            ui->stackedWidget->setCurrentIndex(3);
        else
            ui->stackedWidget->setCurrentIndex(5);
    });
    // 绑定登录操作
    connect(ui->login,&QToolButton::clicked,this,[=](){
        this->api->loginByPassword(ui->phone->text(),ui->password->text());
    });
    connect(api,&Api::loginByPasswordSuccess,this,[=](QString token){
        this->token = token;
        if(token!=NULL)
            ui->stackedWidget->setCurrentIndex(3);
        else
            ui->stackedWidget->setCurrentIndex(5);
        qDebug()<<token;
        api->getUserInfo();
        api->infoCer();
    });
    connect(api,&Api::getUserInfoSuccess,this,&Widget::updateUserInfo);
    connect(api,&Api::searchDishSuccess,this,&Widget::updateDishSearch);
    connect(ui->btn_flash_dish,&QToolButton::clicked,[=](){
        api->getRecommendDish();
    });

    connect(ui->btn_downloadCoreData,&QToolButton::clicked,this,[=](){
       api->downloadCoreData();
    });
    connect(api,&Api::downloadCoreDataSuccess,this,[=](){
        QMessageBox::critical(0 , "下载完成" , "核心数据下载完成", QMessageBox::Ok | QMessageBox::Default,0,0 );
    });
    connect(api,&Api::coverFromServerSuccess,this,[=](){
        ui->syn_method->setText("上次同步方式：从服务器下载数据");
        ui->syn_status->setText("同步状态：已完成");
        ui->syn_time->setText("上次同步时间："+QDateTime::currentDateTime().toString("yyyy 年 MM 月 dd 日 hh:mm:ss"));
    });
    connect(api,&Api::coverByTerminalSuccess,this,[=](){
        ui->syn_method->setText("上次同步方式：上传数据到服务器");
        ui->syn_status->setText("同步状态：已完成");
        ui->syn_time->setText("上次同步时间："+QDateTime::currentDateTime().toString("yyyy 年 MM 月 dd 日 hh:mm:ss"));
    });
    connect(ui->btn_smartSys,&QToolButton::clicked,this,[=](){
        if(bind_id==uid)
        {
            ui->syn_status->setText("同步状态：正在查询同步状态...");
            api->isDirty();
        }
        else{
            ui->syn_status->setText("同步状态：请将冰箱绑定到当前账户");
        }
    });
    connect(api,&Api::isDirtyTrue,this,[=](){
        ui->syn_status->setText("同步状态：正在等待同步选项...");
        QMessageBox box(QMessageBox::Warning, "同步状态", "服务器上数据被修改过，请选择同步方式");
        box.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel|QMessageBox::Save);
        box.setButtonText(QMessageBox::Ok, QString("以本机为主"));
        box.setButtonText(QMessageBox::Save,QString("以服务器为主"));
        box.setButtonText(QMessageBox::Cancel, QString("取消同步"));
        int ret = box.exec();
        switch (ret) {
        case QMessageBox::Ok:
            ui->syn_status->setText("同步状态：正在同步...");
            api->coverByTerminal();
            break;
        case QMessageBox::Save:
            ui->syn_status->setText("同步状态：正在同步...");
            api->coverFromServer();
            break;
        case QMessageBox::Cancel:
            ui->syn_status->setText("同步状态：取消同步");
            break;
        }
    });
    connect(api,&Api::isDirtyFalse,this,[=](){
        ui->syn_status->setText("同步状态：正在同步...");
        api->coverByTerminal();
    });
    connect(ui->btn_flash_option,&QToolButton::clicked,this,&Widget::updateOptioncommit);
    connect(ui->btn_flash_option,&QToolButton::clicked,this,&Widget::updateOptionUncommit);
    connect(ui->btn_flash_remind,&QToolButton::clicked,this,&Widget::updateRemind);
    connect(ui->btn_flash_storage,&QToolButton::clicked,this,&Widget::updateStorage);
    connect(ui->btn_fridge_bind,&QToolButton::clicked,this,[=](){
        bool bOk = false;
        QString pass = QInputDialog::getText(this,
                                             "输入冰箱密码",
                                             "请输入冰箱密码",
                                             QLineEdit::Normal,
                                             "",
                                             &bOk
                                             );

        if (bOk && !pass.isEmpty()) {
            api->bind(pass);
        }
    });
    connect(api,&Api::bindSuccess,this,[=](){
       this->bind_id = this->uid;
       ui->btn_fridge_bind->hide();
    });
    // 设置按钮互斥
    QButtonGroup* left_btns = new QButtonGroup;
    left_btns->addButton(ui->btn_my);
    left_btns->addButton(ui->btn_storage);
    left_btns->addButton(ui->btn_remind);
    left_btns->addButton(ui->btn_diet);
    left_btns->addButton(ui->btn_opt);
    left_btns->setExclusive(true);

    QButtonGroup* opt_btns = new QButtonGroup;
    opt_btns->addButton(ui->btn_opt_commit);
    opt_btns->addButton(ui->btn_opt_uncommit);
    opt_btns->setExclusive(true);

    // 初始化菜谱推荐页面
    ui->stackedWidget_dish->setCurrentIndex(0);
    QButtonGroup* dish_btns = new QButtonGroup;
    dish_btns->addButton(ui->btn_dish_searchPage);
    dish_btns->addButton(ui->btn_dish_recommendPage);
    opt_btns->setExclusive(true);

    connect(ui->btn_dish_searchPage,&QToolButton::clicked,[=](){
        ui->stackedWidget_dish->setCurrentIndex(1);
    });

    connect(ui->btn_dish_recommendPage,&QToolButton::clicked,[=](){
        ui->stackedWidget_dish->setCurrentIndex(0);
    });
    connect(ui->btn_start_rec,&QToolButton::clicked,this,[=](){
       parseRec();
    });


    // 滚动支持 触摸
    ui->dishSearchList->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
    ui->dishSearchList->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel);
    QScroller::grabGesture(ui->dishSearchList,QScroller::LeftMouseButtonGesture);
    ui->list_remind->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
    ui->list_remind->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel);
    QScroller::grabGesture(ui->list_remind,QScroller::LeftMouseButtonGesture);
    ui->list_storage->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
    ui->list_storage->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel);
    QScroller::grabGesture(ui->list_storage,QScroller::LeftMouseButtonGesture);
    ui->list_recommend->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
    ui->list_recommend->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel);
    QScroller::grabGesture(ui->list_recommend,QScroller::LeftMouseButtonGesture);
    ui->listWidget_commit->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
    ui->listWidget_commit->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel);
    QScroller::grabGesture(ui->listWidget_commit,QScroller::LeftMouseButtonGesture);
    ui->listWidget_uncommit->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
    ui->listWidget_uncommit->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel);
    QScroller::grabGesture(ui->listWidget_uncommit,QScroller::LeftMouseButtonGesture);

//    ui->dishSearchList->setWrapping(true);
//    ui->dishSearchList->setFlow(QListView::TopToBottom);


//    setVerticalScrollMode()
//    ui->user_avator->showURLImage("https://tupian.qqw21.com/article/UploadPic/2020-1/202012921182273110.jpg");
}
void Widget::initTime()
{
    // 设置上方计时器
    QTimer *timer_calendar;//用来显示当前日期的定时器
    timer_calendar = new QTimer(this);//new一个QTimer对象
    this->showtime();
    connect(timer_calendar,&QTimer::timeout,this,&Widget::showtime);//连接槽函数
    timer_calendar->start(1000);//每一秒溢出一次进入槽函数
//    timer_calendar->start(60000);//每一秒溢出一次进入槽函数

}
void Widget::initStorage()
{
    updateStorage();
    connect(ui->btn_add_storage,&QToolButton::clicked,[=](){
        StorageAdd* storageAdd = new StorageAdd;
        storageAdd->show();
        connect(storageAdd,&StorageAdd::completed,this,[=](){
           updateStorage();
        });
    });
}
void Widget::initRemind()
{
    updateRemind();
    connect(ui->btn_add_remind,&QToolButton::clicked,[=](){
        RemindAdd* remindAdd = new RemindAdd();
        remindAdd->show();
        connect(remindAdd,&RemindAdd::completed,this,[=](){
           updateRemind();
        });
    });
}
void Widget::initDish()
{
    connect(ui->btn_dish_searchPage,&QToolButton::clicked,[=](){
            ui->stackedWidget_dish->setCurrentIndex(1);
        });

    connect(ui->btn_dish_recommendPage,&QToolButton::clicked,[=](){
        ui->stackedWidget_dish->setCurrentIndex(0);
    });
    connect(ui->dishSearch,&QPushButton::clicked,this,[=](){
        dishPageIndex = 1;
        int n=ui->dishSearchList->count();//获取item的总数
        //删去所有item
        for(int i=0;i<n;i++)
        {
            /*
             使用takeItem(row)函数将QListWidget中的第row个item移除，
             移除需要使用delete手动释放其在堆上占用的空间
            */
            //这里是0，不是i，因为每移除一个item都会导致每个item的row发生变化
            QListWidgetItem *item = ui->dishSearchList->takeItem(0);
            delete item;
        }
        n = dishSearchList.size();
        for(int i=0;i<n;i++)
        {
            qDebug()<<"删除第"<<i<<"个";
            dishSearchList.at(0)->disconnect();
            dishSearchList.at(0)->close();
            dishSearchList.at(0)->deleteLater();
            dishSearchList.removeAt(0);
        }
        ui->dishSearchList->clear();
        dishName = ui->dishKeyword->text();
        api->searchDish(dishName,dishPageSize,dishPageIndex);
    });
    connect(ui->dishSearchList,&MyListWidget::reachedBottom,this,[=](){
        api->searchDish(dishName,dishPageSize,++dishPageIndex);
    });
}
void Widget::initOption()
{

    connect(ui->btn_opt_commit,&QToolButton::clicked,[=](){
        ui->stackedWidget_opt->setCurrentIndex(0);
    });
    connect(ui->btn_opt_uncommit,&QToolButton::clicked,[=](){
        ui->stackedWidget_opt->setCurrentIndex(1);
    });
    connect(ui->btn_option_add,&QToolButton::clicked,[=](){
        OptionAdd* optionAdd = new OptionAdd();
        optionAdd->show();
        connect(optionAdd,&OptionAdd::completed,this,[=](){
            updateOptionUncommit();
        });
    });
    connect(ui->btn_option_commit_deleteAll,&QToolButton::clicked,[=](){
       sql->optionDeleteAllCommit();
       updateOptioncommit();
    });
    connect(ui->btn_option_unCommit_deleteSelect,&QToolButton::clicked,[=](){
        for(int i=0;i<uncommitList.size();i++)
        {
            uncommitList.at(i)->deleteSelectedOption();
        }
        updateOptionUncommit();
    });
    connect(ui->btn_option_commit,&QToolButton::clicked,this,[=](){
        for(int i=0;i<uncommitList.size();i++)
        {
            uncommitList.at(i)->commitSelectedOption();
        }
        updateOptionUncommit();
        updateOptioncommit();
    });
    connect(ui->btn_option_commit_deleteSelected,&QToolButton::clicked,this,[=](){
        for(int i=0;i<commitList.size();i++)
        {
            commitList.at(i)->deleteSelectedOption();
        }
        updateOptionUncommit();
        updateOptioncommit();
    });
    updateOptionUncommit();
    updateOptioncommit();
}
Widget::~Widget()
{
    delete ui;
}

void Widget::showtime()
{
    QDateTime time = QDateTime::currentDateTime();
    QString str = time.toString("yyyy 年 MM 月 dd 日 hh:mm:ss");
//    QString str = time.toString("yyyy 年 MM 月 dd 日 hh:mm");
    ui->label_time->setText(str);
}
void Widget::updateUserInfo(int uid,QString username,QString phone,QString email,QString avatar,int gender){
    this->uid = uid;
    qDebug()<<"冰箱绑定的id:"<<bind_id;
    qDebug()<<"当前用户id:"<<uid;
    if(bind_id==uid)
    {
        ui->btn_fridge_bind->hide();
    }
    ui->user_avator->showURLImage(avatar);
    ui->label_username->setText(username);
    ui->label_phone->setText(phone);
}
void Widget::updateDishRecommend(QList<DishRecommend>* list){
    ui->list_recommend->clear();
    int n = dishRecommendUnitList.size();
    for(int i=0;i<n;i++)
    {
        dishRecommendUnitList.at(0)->disconnect();
        dishRecommendUnitList.at(0)->close();
        dishRecommendUnitList.removeAt(0);
    }
    // 添加推荐菜谱
    for(int i=0;i<list->size();i++)
    {
        DishRecommend p = list->at(i);
        DishRecommendUnit* dishUnit = new DishRecommendUnit(this,p.typeName,p.dishList);
        dishRecommendUnitList.append(dishUnit);
        QListWidgetItem *listItem1 = new QListWidgetItem();
        ui->list_recommend->addItem(listItem1);
        listItem1->setSizeHint(QSize(0, 350));
        ui->list_recommend->setItemWidget(listItem1,dishUnit);
    }
}
void Widget::updateDishSearch(QList<Dish>* dishList){
    qDebug()<<dishList;
    for(int i=0;i<dishList->size();i++)
    {
        Dish p = dishList->at(i);
        DishItem* dishUnit = new DishItem(this,p.id,p.name,p.material,p.detail,p.pic,p.type);
        dishSearchList.append(dishUnit);
        QListWidgetItem *listItem1 = new QListWidgetItem();
        ui->dishSearchList->addItem(listItem1);
        listItem1->setSizeHint(QSize(0, 220));
        ui->dishSearchList->setItemWidget(listItem1,dishUnit);
    }
}
void Widget::updateStorage(){
    ui->list_storage->clear();
    int n = StorageList.size();
    for(int i=0;i<n;i++)
    {
        StorageList.at(0)->disconnect();
        StorageList.at(0)->close();
        StorageList.removeAt(0);
    }
    QList<Storage> result = sql->storageSearchAll();
    qDebug()<<result;
    // 添加一个storage 项目
    for(int i =0 ;i<result.size();i++){
        StorageItem *storageItem = new StorageItem(this);
        StorageList.append(storageItem);
        storageItem->update(result.at(i));
        QListWidgetItem *listItem = new QListWidgetItem();
        listItem->setSizeHint(QSize(0, 125));
        ui->list_storage->addItem(listItem);
        ui->list_storage->setItemWidget(listItem, storageItem);
        connect(storageItem,&StorageItem::deleteSignal,this,[=](){
            ui->list_storage->removeItemWidget(listItem);
            delete listItem;
            storageItem->close();
        });

    }
}
void Widget::updateRemind(){
    ui->list_remind->clear();
    int n = remindItemList.size();
    for(int i=0;i<n;i++)
    {
        remindItemList.at(0)->disconnect();
        remindItemList.at(0)->close();
        remindItemList.removeAt(0);
    }
    QList<Remind> result = sql->remindSearchAll();
    qDebug()<<result;
    // 添加一个storage 项目
    for(int i =0 ;i<result.size();i++){
        RemindItem* remindItem = new RemindItem(this);
        remindItem->update(result.at(i));
        remindItemList.append(remindItem);
        QListWidgetItem *listItem = new QListWidgetItem();
        listItem->setSizeHint(QSize(0, 125));
        ui->list_remind->addItem(listItem);
        ui->list_remind->setItemWidget(listItem, remindItem);
        connect(remindItem,&RemindItem::deleteSignal,this,[=](){
            ui->list_remind->removeItemWidget(listItem);
            delete listItem;
            remindItem->close();
        });
    }
}
void Widget::updateOptionUncommit(){
    int n=ui->listWidget_uncommit->count();//获取item的总数
    //删去所有item
    for(int i=0;i<n;i++)
    {
        /*
         使用takeItem(row)函数将QListWidget中的第row个item移除，
         移除需要使用delete手动释放其在堆上占用的空间
        */
        //这里是0，不是i，因为每移除一个item都会导致每个item的row发生变化
        QListWidgetItem *item = ui->listWidget_uncommit->takeItem(0);
        delete item;
    }
    n = this->uncommitList.size();
    for(int i=0;i<n;i++)
    {
        uncommitList.at(0)->disconnect();
        uncommitList.at(0)->close();
        uncommitList.removeAt(0);
    }
    ui->listWidget_uncommit->clear();
    QList<Option> result = sql->optionSearchUncommitAll();
    qDebug()<<result;
    // 添加操作
    int i = 0;
    int len = result.size();
    while(i<len){
        OptionGroup opg;
        opg.addOption(result.at(i));
        QDateTime temp = result.at(i).datetime;
        // 找到同组的所有操作
        i++;
        while (i<len && result.at(i).datetime==temp)
        {
            opg.addOption(result.at(i));
            i++;
        }

        OptionUnit* unit = new OptionUnit(this);
        uncommitList.append(unit);
        unit->update(opg,false);
        QListWidgetItem *optItem = new QListWidgetItem();
        ui->listWidget_uncommit->addItem(optItem);
        ui->listWidget_uncommit->setItemWidget(optItem,unit);
        optItem->setSizeHint(unit->size());
        optItem->setFlags(Qt::NoItemFlags);
        connect(unit,&OptionUnit::sizeChanged,[=](){
            optItem->setSizeHint(unit->size());
        });
        connect(unit,&OptionUnit::deleteSignal,[=](){
            updateOptionUncommit();
        });
        connect(unit,&OptionUnit::addSignal,[=](){
            updateOptionUncommit();
        });
    }


}
void Widget::updateOptioncommit(){
    int n=ui->listWidget_commit->count();//获取item的总数
    //删去所有item
    for(int i=0;i<n;i++)
    {
        /*
         使用takeItem(row)函数将QListWidget中的第row个item移除，
         移除需要使用delete手动释放其在堆上占用的空间
        */
        //这里是0，不是i，因为每移除一个item都会导致每个item的row发生变化
        QListWidgetItem *item = ui->listWidget_commit->takeItem(0);
        delete item;
    }
    n = this->commitList.size();
    for(int i=0;i<n;i++)
    {
        commitList.at(0)->disconnect();
        commitList.at(0)->close();
        commitList.removeAt(0);
    }
    ui->listWidget_commit->clear();
    QList<Option> result = sql->optionSearchCommitAll();
    qDebug()<<result;
    // 添加操作
    int i = 0;
    int len = result.size();
    while(i<len){
        OptionGroup opg;
        opg.addOption(result.at(i));
        QDateTime temp = result.at(i).datetime;
        // 找到同组的所有操作
        i++;
        while (i<len && result.at(i).datetime==temp)
        {
            opg.addOption(result.at(i));
            i++;
        }

        OptionUnit* unit = new OptionUnit(this);
        commitList.append(unit);
        unit->update(opg,true);
        QListWidgetItem *optItem = new QListWidgetItem();
        ui->listWidget_commit->addItem(optItem);
        ui->listWidget_commit->setItemWidget(optItem,unit);
        optItem->setSizeHint(unit->size());
        optItem->setFlags(Qt::NoItemFlags);
        connect(unit,&OptionUnit::sizeChanged,[=](){
            optItem->setSizeHint(unit->size());
        });
        connect(unit,&OptionUnit::deleteSignal,[=](){
            updateOptionUncommit();
        });
    }
}
void Widget::updateFridgeInfo(Fridge fridge){
    qDebug()<<fridge;
    qDebug()<<"冰箱绑定的id:"<<fridge.userId;
    qDebug()<<"当前用户id:"<<uid;
    if(fridge.userId==uid)
    {
        ui->btn_fridge_bind->hide();
    }
    this->bind_id = fridge.userId;
    ui->fridgeInfo->setCurrentIndex(1);
    ui->fridge_id->setText("冰箱序列号: "+QString::number(fridge.id));
    ui->fridge_name->setText("冰箱名称: "+fridge.name);
    ui->fridge_createTime->setText("生产日期: "+fridge.createTime.toString("yyyy-MM-dd"));
    ui->fridge_activeTime->setText("激活日期: "+fridge.activeTime.toString("yyyy-MM-dd"));
    ui->fridge_guarantee->setText("保修时间: "+QString::number(fridge.guarantee)+" 天");

}
void Widget::startRec(){
    parseRec();
//    p.close();
//    p.start("bash", QStringList() <<"-c" << "sudo sh /home/topeet/Desktop/deployment_on_rk3399/src/run.sh");
}
void Widget::endRec(){
//    p.close();
}
void Widget::parseRec(){
//    QString path = "/home/topeet/Desktop/deployment_on_rk3399/src/output.txt";
    QString path = "output.txt";
    QString labelPath = "labels.txt";
    QFile labelFile(labelPath);
    QMap<QString,int> labels;
    if (labelFile.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        while (!labelFile.atEnd())
        {
            QByteArray line = labelFile.readLine();
            QString str(line);
            qDebug() << str;
            if(str!="\n")
            {
                QStringList s = str.split(" ");
                labels.insert(s[0],s[1].toInt());
            }
        }
        labelFile.close();
    }
    qDebug()<<labels;
    QFile file(path);
    QMap<QString,int> in;
    QMap<QString,int> out;
    if (file.open(QIODevice::ReadWrite | QIODevice::Text))
    {
        while (!file.atEnd())
        {
            QByteArray line = file.readLine();
            QString str(line);
            qDebug() << str;

            if(str!="\n")
            {
                QStringList s = str.split(" ");
                if(s[2].toInt()==1)
                {
                    int amount = s[1].toInt();
                    if(in.contains(s[0]))
                    {
                        amount += in.value(s[0]);
                    }
                    in.insert(s[0],amount);
                }
                else if(s[2].toInt()==0)
                {
                    int amount = s[1].toInt();
                    if(out.contains(s[0]))
                    {
                        amount += out.value(s[0]);
                    }
                    out.insert(s[0],amount);
                }
            }
        }
    }
    file.close();
//    file.open(QFile::WriteOnly|QFile::Truncate);
//    file.close();
    qDebug()<<in;
    qDebug()<<out;
    QMapIterator<QString, int> in_iterator(in);
    QDateTime dateTime = QDateTime::currentDateTime();
    QList<Option> options;
    while (in_iterator.hasNext()) {
        in_iterator.next();
        if(labels.contains(in_iterator.key())){
            qDebug() << in_iterator.key() << ":" << in_iterator.value();
            Option option;
            option.food_id = labels.value(in_iterator.key());
            option.user_id = 0;
            option.amount = in_iterator.value();
            option.datetime = dateTime;
            option.direction = 1;
            option.status = 0;
            options.append(option);
        }
    }
    QMapIterator<QString, int> out_iterator(out);
    while (out_iterator.hasNext()) {
        out_iterator.next();
        if(labels.contains(out_iterator.key()))
        {
            qDebug() << out_iterator.key() << ":" << out_iterator.value();
            Option option;
            option.food_id = labels.value(out_iterator.key());
            option.user_id = 0;
            option.amount = out_iterator.value();
            option.datetime = dateTime;
            option.direction = 0;
            option.status = 0;
            options.append(option);
        }
    }
    sql->optionAdd(options);
    updateOptionUncommit();
}
